<template>
	<view class="parent">
		<view class="cell-item" @click="chooseAvatar">
			<text class="cell-label">头像</text>
				<image class="avatar" :src="user.headPicUrl"></image>
				<z-arrow-right></z-arrow-right>
		</view>

		<view style="margin-top: 30rpx;">
			<z-cell-item label="昵称" :content="user.nick" @click.native="showDialogNick"></z-cell-item>
			<z-cell-item label="性别" :content="user.sex == 2? '女': '男'" :arrow="false"></z-cell-item>
			<z-cell-item label="签名" :content="user.sign" @click.native="showDialogSign"></z-cell-item>
			<z-cell-item label="我的标签" @click.native="toEditTag">
				<view slot='right-icon' class="tag" v-for="(item, index) in tags">{{item}}</view>
			</z-cell-item>
		</view>

		<view style="margin-top: 30rpx;">
			<z-cell-item label="生日">
				<picker slot="right-icon" mode="date" :start="startDate" :end="endDate"
					@change="birthdayConfirm">
					<view>{{user.birthday || '请选择生日'}}</view>
				</picker>
			</z-cell-item>
			<z-cell-item label="身高">
				<picker slot="right-icon" :value="heightIndex" :range="heightList" range-key="height"
					@change="heightConfirm">
					<view>{{user.heightStr || '请选择身高'}}</view>
				</picker>
			</z-cell-item>
			<z-cell-item label="体重">
				<picker slot="right-icon" :value="weightIndex" :range="weightList" range-key="weight"
					@change="weightConfirm">
					<view>{{user.weightStr || '请选择体重'}}</view>
				</picker>
			</z-cell-item>
			<z-cell-item label="年收入">
				<picker slot="right-icon" :value="incomeIndex" :range="incomeList" range-key="name"
					@change="incomeConfirm">
					<view>{{user.incomeStr || '请选择年收入'}}</view>
				</picker>
			</z-cell-item>
			<z-cell-item label="学历">
				<picker slot="right-icon" :value="educationIndex" :range="educationList" range-key="name"
					@change="educationConfirm">
					<view>{{user.educStr || '请选择学历'}}</view>
				</picker>
			</z-cell-item>
			<z-cell-item label="职业">
				<picker slot="right-icon" mode=multiSelector :value="workerindex" :range="workerList" range-key="name"
					@columnchange="workerChange" @change="workerConfirm">
					<view>{{user.careerStr || '请选择职位'}}</view>
				</picker>
			</z-cell-item>
		</view>

		<view style="margin: 30rpx 0; background-color: white; padding: 30rpx;">
			<uni-file-picker limit="3" title="个人形象照" :source-type="sourceType" @select="selectPhoto"
				@delete="deletePhoto" ref="files" :auto-upload="false" :value="photos"></uni-file-picker>
		</view>

		<uni-popup type="bottom" ref="edit">
			<view class="popup-view">
				<view class="popup-title">
					{{editTitle}}
				</view>
				<view class="popup-content">
					<input v-model="editContent" style="padding: 20rpx;"/>
				</view>
				<view class="popup-bottom">
					<z-button text='确定' @click.native="editConfirm"></z-button>
				</view>
			</view>
		</uni-popup>

	</view>

</template>

<script>
	import {
		ossUpload,
		getFileName
	} from '@/js_sdk/jason-alioss-upload/oss.js'
	import constant from '@/common/constant.js';

	export default {
		data() {
			return {
				userId: '',
				user: {},
				photos: [],
				introPicIds: '',
				sourceType: ['album', 'camera'],
				currentPicIndex: 0,
				editType: '', //1.昵称；2.个性签名
				editTitle: '',
				editContent: '',
				nick: '',
				tags: [],
				heightIndex: 0,
				heightList: [],
				weightIndex: 0,
				weightList: [],
				incomeIndex: 0,
				incomeList: [],
				educationIndex: 0,
				educationList: [],
				workerindex: [0, 0],
				workerList: [],
				subWorkerList: [],
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		onLoad(option) {
			this.userId = option.userId;
			this.requestUser();
			this.requestDict();
		},
		methods: {
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year - 18;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			chooseAvatar() {
				const carmeraAvatar = uni.getStorageSync('carmeraAvatar');
				if (carmeraAvatar) {
					this.uploadOOS()
					return
				}
				uni.showModal({
					content: '拍照功能用于上传头像',
					success: res => {
						if (res.confirm) {
							uni.setStorageSync('carmeraAvatar', true);
							this.uploadOOS()
						}
					}
				})
			},
			uploadOOS() {
				uni.chooseImage({
					count: 1,
					crop:{
						width: 200,
						height: 200
					},
					success: async (file) => {
						let dir = 'userinfo'
						let fileName = getFileName(file.tempFilePaths[0]);
						const {
							success,
							data
						} = await ossUpload(file.tempFilePaths[0], fileName, dir)
						console.log("data: " + JSON.stringify(data));
						if (success) {
							this.requestFile(dir, fileName, data)
						} else {
							uni.showToast({
								icon: 'none',
								title: data
							})
						}
					}
				});
			},
			async requestFile(pathKey, fileNameKey, picUrl) {
				let params = {
					pathKey: pathKey,
					userIdKey: this.user.id,
					fileNameKey: fileNameKey
				}
				let res = await this.$common.post('/api/ossSts/callBackFiInfo', params)
				if (200 == res.code) {
					this.requestAvatar(res.data, picUrl)
				}
			},
			// 新增图片
			selectPhoto(event) {
				this.introPicIds = ''
				this.currentPicIndex = 0
				event.tempFilePaths.forEach(async (file, index) => {
					console.log("file: " + JSON.stringify(file));
					let dir = 'userinfo'
					let fileName = getFileName(file);
					const {
						success,
						data
					} = await ossUpload(file, fileName, dir)
					if (success) {
						this.requestFilePhoto(dir, fileName, data, index, event.tempFilePaths.length)
					} else {
						this.currentPicIndex++;
						uni.showToast({
							icon: 'none',
							title: data
						})
					}
				});
			},
			async requestFilePhoto(pathKey, fileNameKey, picUrl, index, length) {
				let params = {
					pathKey: pathKey,
					userIdKey: this.user.id,
					fileNameKey: fileNameKey
				}
				let res = await this.$common.post('/api/ossSts/callBackFiInfo', params)
				if (200 == res.code) {
					this.currentPicIndex++;
					this.photos.push({
						url: picUrl,
						id: res.data
					});
					if (this.introPicIds) {
						this.introPicIds += ',' + res.data;
					} else {
						this.introPicIds = res.data;
					}
					if (this.currentPicIndex == length) {
						this.requestUploadPhoto(1)
					}
				} else {
					this.currentPicIndex++;
				}
			},
			async requestUploadPhoto(useFileType) {
				let params = {
					useFileType: useFileType, //文件删除标识 1 上传  2删除
					introPicIds: this.introPicIds,
					id: this.user.id
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {}
			},
			async deletePhoto(event) {
				this.introPicIds = ''
				this.photos = this.photos.filter(item => {
					if (item.url === event.tempFilePath) {
						this.introPicIds = item.id
					}
					return item.url !== event.tempFilePath;
				})
				this.requestUploadPhoto(2)
			},

			showDialogNick() {
				this.editType = "1";
				this.editTitle = '修改昵称';
				this.editContent = this.user.nick;
				this.$refs.edit.open()
			},
			showDialogSign() {
				this.editType = "2";
				this.editTitle = '修改个性签名';
				this.editContent = this.user.sign;
				this.$refs.edit.open()
			},
			editConfirm() {
				this.$refs.edit.close()
				if ("1" == this.editType) {
					this.requestNick(this.editContent);
				}
				if ("2" == this.editType) {
					this.requestSign(this.editContent);
				}
				console.log(this.editContent);
			},

			birthdayConfirm(event) {
				let brithday = event.detail.value;
				this.requestBirthday(brithday);
			},
			heightConfirm(event) {
				this.requestHeight(this.heightList[event.detail.value]);
			},
			weightConfirm(event) {
				this.requestWeight(this.weightList[event.detail.value]);
			},
			incomeConfirm(event) {
				this.requestIncome(this.incomeList[event.detail.value]);
			},
			educationConfirm(event) {
				this.requestEducation(this.educationList[event.detail.value]);
			},
			workerChange(event) {
				console.log(JSON.stringify(event.detail));
				this.workerindex[event.detail.column] = event.detail.value;
				if (event.detail.column == 0) {
					this.workerList[1] = this.subWorkerList[event.detail.value];
					this.workerindex[1] = 0;
				}
				console.log(JSON.stringify(this.workerList));
				this.$forceUpdate();
			},
			workerConfirm(event) {
				const item = this.workerList[1][event.detail.value[1]];
				this.requestWorker(item);
			},

			toEditTag() {
				uni.navigateTo({
					url: '/main/user/edit/tag/tag?userId=' + this.userId + "&tagIds=" + this.user.tagIds,
					events: {
						sendTags: res => {
							if (res.names) {
								this.tags = res.names.split(',');
								this.user.tagIds = res.ids;
							}
						}
					},
					fail: (error) => {
						console.log("error: " + JSON.stringify(error));
					}
				})
			},

			async requestUser() {
				let res = await this.$common.get('/api/getLoginUser');
				if (200 == res.code) {
					this.user = res.data;
					//形象照
					if (this.user.introPicIdUrl) {
						let ids = this.user.introPicIds.split(',')
						this.user.introPicIdUrl.forEach((item, index) => {
							this.photos.push({
								url: item,
								id: ids[index]
							});
						});
					}
					if (this.user.tagIdList) {
						this.tags = this.user.tagIdList;
					}
				}
			},
			async requestDict() {
				let res = await this.$common.get('/api/dict/detail');
				if (200 == res.code) {
					this.heightList = res.data.dictHeights
					this.weightList = res.data.dictWeights
					this.incomeList = res.data.dictIncomes
					this.educationList = res.data.dictEducs
					let workerOne = [];
					res.data.dictCareerNodeVos.forEach(item => {
						workerOne.push(item);
						this.subWorkerList.push(item.children);
					});
					this.workerList.push(workerOne);
					this.workerList.push(this.subWorkerList[0]);
				}
			},
			async requestAvatar(picId, picUrl) {
				let params = {
					headPicId: picId,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.headPicUrl = picUrl;
					uni.setStorageSync("userPic", picUrl);
				}
			},
			async requestNick(nick) {
				let params = {
					nick: nick,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.nick = nick;
					uni.setStorageSync("userName", nick);
				}
			},
			async requestSign(sign) {
				let params = {
					sign: sign,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.sign = sign;
				}
			},
			async requestBirthday(birthday) {
				let params = {
					birthday: birthday,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.birthday = birthday;
				}
			},
			async requestHeight(data) {
				console.log("data: " + JSON.stringify(data));
				let params = {
					heightId: data.id,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.heightStr = data.height + data.unit;
				}
			},
			async requestWeight(data) {
				let params = {
					weightId: data.id,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.weightStr = data.weight + data.unit;
				}
			},
			async requestIncome(data) {
				let params = {
					incomeId: data.id,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.incomeStr = data.name + data.unit;
				}
			},
			async requestEducation(data) {
				let params = {
					educId: data.id,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.educStr = data.name;
				}
			},
			async requestWorker(data) {
				let params = {
					careerId: data.id,
					id: this.userId
				}
				let res = await this.$common.post('/api/user/updateUser', params);
				if (200 == res.code) {
					this.user.careerStr = data.name;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>

	.cell-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100wh;
		padding:30rpx;
		background-color: white;
		justify-content: space-between;

		.cell-label {
			color: #555;
			flex: 1;
		}
		.avatar {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
		}
	}

	.tag {
		margin: 5rpx;
		padding: 10rpx 20rpx;
		background-color: #009fff;
		border-radius: 50rpx;
		color: #fff;
		font-size: 24rpx;
	}

	.popup-view {
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 10rpx 30rpx;
		box-sizing: border-box;
		height: 400rpx;
		background-color: white;
		border-top-right-radius: 30rpx;
		border-top-left-radius: 30rpx;

		.popup-title {
			font-size: 36rpx;
			color: #222;
			margin-top: 10rpx;
			text-align: center;
		}

		.popup-content {
			flex: 1;
			display: flex;
			flex-direction: row;
			margin: 30rpx 0;
			border:  1px solid #eaeaea;
			border-radius: 10rpx;
		}

		.popup-bottom {
			margin: 0 30rpx;
		}
	}
</style>